// pages/cart/cart.js
const app = getApp()

Page({
  data: {
    cartItems: [],
    selectedItems: [],
    isAllSelected: false,
    totalPrice: '0.00',
    loading: false
  },

  onLoad() {
    this.loadCartData()
  },

  onShow() {
    // 更新自定义tabBar的选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      });
    }
    
    this.loadCartData();
  },

  onPullDownRefresh() {
    this.loadCartData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载购物车数据
  async loadCartData() {
    if (!app.globalData.token) {
      this.setData({
        cartItems: [],
        selectedItems: [],
        isAllSelected: false,
        totalPrice: '0.00'
      })
      return
    }

    this.setData({ loading: true })

    try {
      const response = await app.request({
        url: '/orders/cart/'
      })

      if (response.success) {
        const cartItems = response.data.items.map(item => ({
          ...item,
          checked: false
        }))

        this.setData({
          cartItems,
          selectedItems: [],
          isAllSelected: false,
          totalPrice: '0.00'
        })
      } else {
        app.showToast(response.message || '加载失败', 'none')
      }
    } catch (error) {
      console.error('加载购物车失败:', error)
      app.showToast('加载失败，请重试', 'none')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 商品选择
  onItemCheck(e) {
    const itemId = parseInt(e.currentTarget.dataset.id)
    const { cartItems } = this.data
    
    const updatedItems = cartItems.map(item => {
      if (item.id === itemId) {
        return { ...item, checked: !item.checked }
      }
      return item
    })

    this.setData({ cartItems: updatedItems })
    this.updateSelection()
  },

  // 全选/取消全选
  onSelectAll() {
    const { cartItems, isAllSelected } = this.data
    const newSelectState = !isAllSelected
    
    const updatedItems = cartItems.map(item => ({
      ...item,
      checked: newSelectState
    }))

    this.setData({ 
      cartItems: updatedItems,
      isAllSelected: newSelectState
    })
    this.updateSelection()
  },

  // 更新选中状态和总价
  updateSelection() {
    const { cartItems } = this.data
    const selectedItems = cartItems.filter(item => item.checked)
    const isAllSelected = cartItems.length > 0 && selectedItems.length === cartItems.length
    
    // 计算总价
    let totalPrice = 0
    selectedItems.forEach(item => {
      const price = item.spec_price || item.flower.price
      totalPrice += price * item.quantity
    })

    this.setData({
      selectedItems,
      isAllSelected,
      totalPrice: totalPrice.toFixed(2)
    })
  },

  // 数量变更
  async onQuantityChange(e) {
    const { id, type } = e.currentTarget.dataset
    const { cartItems } = this.data
    
    const item = cartItems.find(item => item.id === id)
    if (!item) return

    let newQuantity = item.quantity
    if (type === 'minus' && newQuantity > 1) {
      newQuantity--
    } else if (type === 'plus') {
      newQuantity++
    } else {
      return
    }

    try {
      const response = await app.request({
        url: `/orders/cart/${id}/`,
        method: 'PUT',
        data: { quantity: newQuantity }
      })

      if (response.success) {
        // 更新本地数据
        const updatedItems = cartItems.map(cartItem => {
          if (cartItem.id === id) {
            return { ...cartItem, quantity: newQuantity }
          }
          return cartItem
        })

        this.setData({ cartItems: updatedItems })
        this.updateSelection()
        
        // 更新全局购物车数量
        app.getCartCount()
      } else {
        app.showToast(response.message || '更新失败', 'none')
      }
    } catch (error) {
      console.error('更新数量失败:', error)
      app.showToast('更新失败，请重试', 'none')
    }
  },

  // 删除商品
  onDeleteItem(e) {
    const itemId = parseInt(e.currentTarget.dataset.id)
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这件商品吗？',
      success: (res) => {
        if (res.confirm) {
          this.deleteCartItem(itemId)
        }
      }
    })
  },

  // 删除购物车商品
  async deleteCartItem(itemId) {
    try {
      const response = await app.request({
        url: `/orders/cart/${itemId}/`,
        method: 'DELETE'
      })

      if (response.success) {
        // 从本地数据中移除
        const { cartItems } = this.data
        const updatedItems = cartItems.filter(item => item.id !== itemId)
        
        this.setData({ cartItems: updatedItems })
        this.updateSelection()
        
        // 更新全局购物车数量
        app.getCartCount()
        
        app.showToast('删除成功')
      } else {
        app.showToast(response.message || '删除失败', 'none')
      }
    } catch (error) {
      console.error('删除商品失败:', error)
      app.showToast('删除失败，请重试', 'none')
    }
  },

  // 商品点击
  onProductTap(e) {
    const productId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/detail/detail?id=${productId}`
    })
  },

  // 去购物
  onGoShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 结算
  onCheckout() {
    const { selectedItems } = this.data
    
    if (selectedItems.length === 0) {
      app.showToast('请选择要结算的商品', 'none')
      return
    }

    // 获取选中商品的ID
    const cartIds = selectedItems.map(item => item.id).join(',')
    
    wx.navigateTo({
      url: `/pages/order/order?cartIds=${cartIds}`
    })
  }
})